package com.qf.security1.service.impl;

import com.qf.security1.domain.User;
import com.qf.security1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /*
        String username 就是前端传递过来的用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //我们自己数据库对应的User
        User user = userMapper.findByUsername(username);

        if (user != null) {

            List<String> roles = userMapper.findRoleNamesByUsername(username);

            //返回的是security封装信息的User
            return org.springframework.security.core.userdetails.User
                    //用户名
                    .withUsername(user.getUsername())
                    //密码（数据库中查出来的）
                    .password(user.getPassword())
                    /*
                        设置权限：二选一
                            .roles： 给的值不可以是ROLE_开头，内部会自动在我们给的值的基础上拼接上ROLE_
                            .authorities 给的值要以ROLE_开头
                     */

                    //要去查询当前用户具备的角色名称
                    .roles(roles.toArray(new String[0]))
                    .build();
        }

        return null;
    }
}
